<?php

class Character extends Core {
	public function get($character = null, $field = null)	{
		$rs = $this->Database->query('SELECT
			MEMB_STAT.ConnectStat,
			MEMB_STAT.ConnectTM AS last_connection,
			MEMB_STAT.ServerName AS server,
			AccountCharacter.GameIDC,
			Character.Name AS name,
			Character.' . $this->Config->columns['resets'] . ' AS resets,
			Character.' . $this->Config->columns['avatar'] . ' AS avatar,
			Character.cLevel AS level,
			Character.Experience AS experience,
			Character.Class AS class,
			Character.PkLevel AS pk_level,
			Character.PkCount AS pk_count,
			Character.AccountID AS account,
			Character.LevelUpPoint AS points,
			Character.MapNumber AS map,
			Character.MapPosY AS y,
			Character.MapPosX AS x,
			Character.CtlCode AS code,
			Character.Strength AS strength,
			Character.Dexterity AS dexterity,
			Character.Vitality AS vitality,
			Character.Energy AS energy,
			Character.Leadership AS leadership,
			Character.Money AS money,
			GuildMember.G_Name AS guild
			FROM MEMB_STAT 
			INNER JOIN AccountCharacter ON (MEMB_STAT.memb___id = AccountCharacter.ID COLLATE DATABASE_DEFAULT) 
			INNER JOIN Character ON (MEMB_STAT.memb___id = Character.AccountID COLLATE DATABASE_DEFAULT)
			LEFT JOIN GuildMember ON (Character.Name = GuildMember.Name COLLATE DATABASE_DEFAULT)
			WHERE Character.Name = %s
		', $character)->fetch();
		$data = array();
		if (!empty($rs)) {
			$data = $rs;
			$data['status'] = $data['ConnectStat'] > 0 && $data['GameIDC'] == $data['name'] ? 1: 0;
			$data['guild'] = is_null($data['guild']) ? '---' : $data['guild'];
			$data['map_name'] = Convert::map($data['map']);
			$data['class_name'] = Convert::race($data['class']);
			$data['last_connection'] = date('d-m-Y H:i:s', strtotime($data['last_connection']));
			$data['avatar'] = $data['avatar'];
			$data['avatar_path'] = Convert::avatar($data['avatar']);
			unset($data['GameIDC'], $data['ConnectStat']);
		}
		return is_null($field) ? $data : $data[$field];
	}
	
	public function in_account($character = null, $account = null) {
		$rs = $this->Database->query('SELECT COUNT(1) AS total FROM Character WHERE Name = %s AND AccountID = %s', $character, $account)->fetch();
		return $rs['total'];
	}
	
	public function team() {
		$rs = $this->Database->query('SELECT 
			MEMB_STAT.ConnectStat,
			AccountCharacter.GameIDC,
			Character.Name AS name
			FROM MEMB_STAT 
			INNER JOIN AccountCharacter ON (MEMB_STAT.memb___id = AccountCharacter.ID) 
			INNER JOIN Character ON (MEMB_STAT.memb___id = Character.AccountID) 
			WHERE Character.CtlCode > 7
		')->fetch_all();
		foreach ($rs as $key => $value) {
			$data[$key] = $value;
			$data[$key]['status'] = $data[$key]['ConnectStat'] > 0 && $data[$key]['GameIDC'] == $data[$key]['name'] ? 1 : 0;
			unset($data[$key]['ConnectStat'], $data[$key]['GameIDC']);
		}
		return $data;
	}
}

?>